package com.cjet.nissan

import android.R.attr.host
import android.R.attr.port
import android.os.Bundle
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.cjet.nissan.tcp.INetty
import com.cjet.nissan.tcp.ImpNetty
import io.netty.channel.ChannelHandlerContext


class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

//        lianjie()
//        lianjie()
//        lianjie()


    }

    fun lianjie(){

        // 初始化Netty
        val mNetty: ImpNetty = ImpNetty(object : INetty.OnChannelHandler {
            override fun onMessageReceived(ctx: ChannelHandlerContext?, msg: Any?) {

            }

            override  fun onExceptionCaught(ctx: ChannelHandlerContext?, e: Throwable?) {

            }
        }, true)

        // 设置连接监听
        mNetty.setOnConnectListener(object : INetty.OnConnectListener {
            override fun onSuccess() {
                // TODO 连接成功
            }

            override fun onFailure(e: Throwable?) {
                // TODO 连接失败
            }
        })

        // 设置发送消息监听
        mNetty.setOnSendMessageListener(object : INetty.OnSendMessageListener{
            override  fun onSendMessage(msg: Any?) {
                // TODO 发送的消息
            }

            override  fun onException(e: Throwable?) {
                //TODO 异常
            }
        })


        // 初始化后，建立连接
        mNetty.connect("192.168.10.114", 6000)


        //---------------------
        // ...
        // 发送消息
        mNetty.sendMessage("0XAFDS")
        mNetty.sendMessage("0XAADDAFDS")
        mNetty.sendMessage("0XDSDAFDS")
        mNetty.sendMessage("0XDSDAFDS")
        mNetty.sendMessage("0XASDADFDS")
        mNetty.sendMessage("0XAFDS")
        mNetty.sendMessage("0XAFDS")
        mNetty.sendMessage("0XAFDS")


//        //---------------------
//        // ...
//        // 断开连接
//        mNetty.disconnect()


        //---------------------
        // ...
        // 重连
        mNetty.reconnect(3)


//        //---------------------
//        // ...
//        // 关闭连接
//        mNetty.close()
    }

}